package me.helllp.bootman.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * Spring MVC 配置
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
	@Autowired
	private AdminConfig config; 
	
	/**
     * 登录session key
     */
    public final static String SESSION_KEY = "login_user";
    
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addWebRequestInterceptor(new WebRequestInterceptor() {
			

			public void postHandle(WebRequest request, ModelMap model) throws Exception {
				if(model == null){
					model = new ModelMap();
				}
				
				//	对全局返回设置远程的服务地址
				model.addAttribute(AdminConfig.REMOTE_URL, config.getRemoteUrl());
			}
			
			public void afterCompletion(WebRequest request, Exception ex) throws Exception {
			}

			public void preHandle(WebRequest request) throws Exception {
			}
		});
		
//		//	增加安全方面的处理
//		registry.addInterceptor(new HandlerInterceptorAdapter(){
//			@Override
//			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
//					throws Exception {
//
//				HttpSession session = request.getSession();
//				if(session.getAttribute(SESSION_KEY) != null){
//					return true;
//				}
//				
//				response.sendRedirect("/login");
//				return false;
//			}
//		}).excludePathPatterns("/error").excludePathPatterns("/login**").addPathPatterns("/**");
	}
}
